﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Drawing.Imaging;


namespace Fitness_club
{
    public partial class addpladfn : Form
    {
        Database db;
        private FilterInfoCollection webcam;
        private VideoCaptureDevice cam;

        MemoryStream ms;

        byte[] photo_aray;

        private HashSet<Control> errorControls = new HashSet<Control>();


        public static string constr = ConfigurationManager.AppSettings["ConStr"];//ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
        SqlConnection con = new SqlConnection(constr);

        private int editMemberId = -1;

        public addpladfn()
        {
            InitializeComponent();
            checkBoxExistingMember.Enabled = true;
            webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            foreach (FilterInfo VideoCaptureDevice in webcam)
            {
                comboBox4.Items.Add(VideoCaptureDevice);
            }
            if (webcam.Count > 0)
            {
                comboBox4.SelectedIndex = 0;
                startCamera();
            }
            getMemberId();
           
        }

        public addpladfn(int memberId)
        {
            InitializeComponent();
            this.editMemberId = memberId;
            fetchMemberById(this.editMemberId);
            btnGo.Text = "Update";
            btnCaptureImage.Text = "Retake";
            

            webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            foreach (FilterInfo VideoCaptureDevice in webcam)
            {
                comboBox4.Items.Add(VideoCaptureDevice);
            }
            comboBox4.SelectedIndex = 0;
        }


        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

        private void addpladfn_Load(object sender, EventArgs e)
        {
            fetchMemberPlan();
            textBoxMemId.Tag = "Member id should not be empty";
            txtFirstName.Tag = "Please enter first name";
            txtLastName.Tag = "Please enter last address";
            txtContactNo.Tag = "Please enter contact number";

            errorProvider1.BlinkStyle = ErrorBlinkStyle.NeverBlink;

            ValidateTextBox(textBoxMemId, EventArgs.Empty);
            ValidateTextBox(txtFirstName, EventArgs.Empty);
            ValidateTextBox(txtLastName, EventArgs.Empty);
            ValidateTextBox(txtContactNo, EventArgs.Empty);
            textBoxMemId.ReadOnly = true;
            //if (!DesignMode)
            //{
               
            //}
        }

        private void ValidateTextBox(object sender, EventArgs e)
        {
            var textBox = sender as TextBox;
            if (textBox.Text == "")
            {
                errorProvider1.SetError(textBox, (string)textBox.Tag);
                errorControls.Add(textBox);
            }
            else
            {
                errorProvider1.SetError(textBox, null);
                errorControls.Remove(textBox);
            }
            btnGo.Enabled = errorControls.Count == 0;
        }

        public void startCamera()
        {                       
            cam = new VideoCaptureDevice(webcam[comboBox4.SelectedIndex].MonikerString);
            cam.NewFrame += new NewFrameEventHandler(cam_NewFrame);
            cam.Start();            
        }

        public void stopCamera()
        {
            if (cam !=null && cam.IsRunning)
            {
                cam.Stop();
            }
        }

        private void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap bit = (Bitmap)eventArgs.Frame.Clone();
            pictureBoxMember.Image = bit;
        }

        private void btnCaptureImage_Click(object sender, EventArgs e)
        {
            if (btnCaptureImage.Text == "Capture")
            {
                btnCaptureImage.Text = "Retake";
                stopCamera();
            }
            else
            {
                btnCaptureImage.Text = "Capture";
                startCamera();
            }
        }
        
        private void btnGo_Click(object sender, EventArgs e)
        {
            if (btnGo.Text == "Save")
            {
                DateTime DOB;
                DOB = dateTimePickerDOB.Value;

                DateTime DOJ;
                DOJ = dateTimePickerDOJ.Value;

                try
                {
                    con.Open();

                    SqlCommand objCmd = new SqlCommand();
                    objCmd.Connection = con;
            String dateOfBirth = DOB.Date.ToString();
                    SqlParameter param = new SqlParameter();
            String dateOfJoining = DOJ.Date.ToString();

                    objCmd.CommandType = CommandType.StoredProcedure;
                    objCmd.CommandText = "pr_insert_member_details";


                    param = new SqlParameter();
                    param.ParameterName = "@vMemId";
                    param.SqlDbType = SqlDbType.VarChar;
                    param.Value = textBoxMemId.Text.ToString() + "";
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vFirtsName";
                    param.SqlDbType = SqlDbType.VarChar;
                    param.Value = txtFirstName.Text.ToString()+"";
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vLastName";
                    param.SqlDbType = SqlDbType.VarChar;
                    param.Value = txtLastName.Text.ToString()+"";
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vGender";
                    param.SqlDbType = SqlDbType.VarChar;
                    if (rdoMale.Checked == true)
                    {
                        param.Value = "Male";
                    }
                    else if (rdoFemale.Checked == true)
                    {
                        param.Value = "Female";
                    }
                    else
                    {
                        param.Value = "";
                    }
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vdob";
                    param.SqlDbType = SqlDbType.Date;
                    param.Value = DateTime.Parse(DOB.ToShortDateString());//txtDOB.Text.ToString();
                    objCmd.Parameters.Add(param);

                    int age=0;
                    if(txtAge.Text.Length>0){
                        int.Parse(txtAge.Text);
                    }
                    param = new SqlParameter();
                    param.ParameterName = "@iAge";
                    param.SqlDbType = SqlDbType.Int;
                    param.Value = age;
                    objCmd.Parameters.Add(param);

                    float height=0;
                    if(txtHeight.Text.Length>0){
                        height=float.Parse(txtHeight.Text.ToString());
                    }
                    
                    param = new SqlParameter();
                    param.ParameterName = "@fHeight";
                    param.SqlDbType = SqlDbType.Float;
                    param.Value = height;
                    objCmd.Parameters.Add(param);

                    float weight=0;
                    if(txtWeight.Text.Length>0){
                        weight= float.Parse(txtWeight.Text.ToString());
                    }
                    param = new SqlParameter();
                    param.ParameterName = "@fweight";
                    param.SqlDbType = SqlDbType.Float;
                    param.Value =weight;
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vBloodPressure";
                    param.SqlDbType = SqlDbType.VarChar;
                    if (rdoBPYes.Checked == true)
                    {
                        param.Value = "Yes";
                    }
                    else
                    {
                        param.Value = "No";
                    }
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vSugar";
                    param.SqlDbType = SqlDbType.VarChar;
                    if (rdoSugarYes.Checked == true)
                    {
                        param.Value = "Yes";
                    }
                    else
                    {
                        param.Value = "No";
                    }
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vHealthIssues";
                    param.SqlDbType = SqlDbType.VarChar;
                    param.Value = txtHealthIssue.Text.ToString();
                    objCmd.Parameters.Add(param);


                    param = new SqlParameter();
                    param.ParameterName = "@vContatcNo";
                    param.SqlDbType = SqlDbType.VarChar;
                    param.Value = txtContactNo.Text.ToString();
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vAddress";
                    param.SqlDbType = SqlDbType.VarChar;
                    param.Value = txtAddress.Text.ToString();
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vdateofjoining";
                    param.SqlDbType = SqlDbType.Date;
                    param.Value = DateTime.Parse(DOJ.ToShortDateString()); //txtDOJ.Text.ToString();
                    objCmd.Parameters.Add(param);


                    param = new SqlParameter();
                    param.ParameterName = "@iMemPlan";
                    param.SqlDbType = SqlDbType.Int; //int.Parse(cmbPackage.SelectedValue.ToString());
                    param.Value = int.Parse(cmbPackage.SelectedValue.ToString());
                    objCmd.Parameters.Add(param);


                    param = new SqlParameter();
                    param.ParameterName = "@image";
                    param.SqlDbType = SqlDbType.Binary;
                    param.Value = conv_photo();
                    objCmd.Parameters.Add(param);

                    objCmd.ExecuteNonQuery();
                    MessageBox.Show("MEMBER Insert successfully", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Hide();
                    stopCamera();
                }
                catch
                {
                    MessageBox.Show("MEMBER Insert Failed, Try Again", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    con.Close();
                }
            }
            else if (btnGo.Text == "Update")
            {
                DateTime DOB;
                DOB = dateTimePickerDOB.Value;

                DateTime DOJ;
                DOJ = dateTimePickerDOJ.Value;

                try
                {
                    con.Open();

                    SqlCommand objCmd = new SqlCommand();
                    objCmd.Connection = con;

                    SqlParameter param = new SqlParameter();

                    objCmd.CommandType = CommandType.StoredProcedure;
                    objCmd.CommandText = "pr_update_member";

                    param = new SqlParameter();
                    param.ParameterName = "@id";
                    param.SqlDbType = SqlDbType.BigInt;
                    param.Value = editMemberId;
                    objCmd.Parameters.Add(param);
                    
                    param = new SqlParameter();
                    param.ParameterName = "@vFirtsName";
                    param.SqlDbType = SqlDbType.VarChar;
                    param.Value = txtFirstName.Text.ToString();
                    objCmd.Parameters.Add(param);


                    param = new SqlParameter();
                    param.ParameterName = "@vLastName";
                    param.SqlDbType = SqlDbType.VarChar;
                    param.Value = txtLastName.Text.ToString();
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vGender";
                    param.SqlDbType = SqlDbType.VarChar;
                    if (rdoMale.Checked == true)
                    {
                        param.Value = "Male";
                    }
                    else
                    {
                        param.Value = "Female";
                    }
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vdob";
                    param.SqlDbType = SqlDbType.Date;
                    param.Value = DateTime.Parse(DOB.ToShortDateString());//txtDOB.Text.ToString();
                    objCmd.Parameters.Add(param);


                    param = new SqlParameter();
                    param.ParameterName = "@iAge";
                    param.SqlDbType = SqlDbType.Int;
                    param.Value = int.Parse(txtAge.Text);
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@fHeight";
                    param.SqlDbType = SqlDbType.Float;
                    param.Value = float.Parse(txtHeight.Text.ToString() + "");
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@fWeight";
                    param.SqlDbType = SqlDbType.Float;
                    param.Value = float.Parse(txtWeight.Text.ToString() + "");
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vBloodPressure";
                    param.SqlDbType = SqlDbType.VarChar;
                    if (rdoBPYes.Checked == true)
                    {
                        param.Value = "Yes";
                    }
                    else
                    {
                        param.Value = "No";
                    }
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vSugar";
                    param.SqlDbType = SqlDbType.VarChar;
                    if (rdoSugarYes.Checked == true)
                    {
                        param.Value = "Yes";
                    }
                    else
                    {
                        param.Value = "No";
                    }
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vHealthIssues";
                    param.SqlDbType = SqlDbType.VarChar;
                    param.Value = txtHealthIssue.Text.ToString();
                    objCmd.Parameters.Add(param);


                    param = new SqlParameter();
                    param.ParameterName = "@vContatcNo";
                    param.SqlDbType = SqlDbType.VarChar;
                    param.Value = txtContactNo.Text.ToString();
                    objCmd.Parameters.Add(param);

                    param = new SqlParameter();
                    param.ParameterName = "@vAddress";
                    param.SqlDbType = SqlDbType.VarChar;
                    param.Value = txtAddress.Text.ToString();
                    objCmd.Parameters.Add(param);

                    
                    param = new SqlParameter();
                    param.ParameterName = "@vDateofJoining";
                    param.SqlDbType = SqlDbType.Date;
                    param.Value = DateTime.Parse(DOJ.ToShortDateString()); //txtDOJ.Text.ToString();
                    objCmd.Parameters.Add(param);


                    param = new SqlParameter();
                    param.ParameterName = "@iMemPlan";
                    param.SqlDbType = SqlDbType.Int; //int.Parse(cmbPackage.SelectedValue.ToString());
                    param.Value = int.Parse(cmbPackage.SelectedValue.ToString());
                    objCmd.Parameters.Add(param);


                    param = new SqlParameter();
                    param.ParameterName = "@image";
                    param.SqlDbType = SqlDbType.Binary;
                    param.Value = conv_photo();
                    objCmd.Parameters.Add(param);

                    objCmd.ExecuteNonQuery();
                    MessageBox.Show("MEMBER updated successfully", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Hide();
                }
                catch
                {
                    MessageBox.Show("MEMBER update Failed, Try Again", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    con.Close();
                }
            }
           
            
        }



      

        private void txtFirstName_TextChanged(object sender, EventArgs e)
        {
            ValidateTextBox(txtFirstName, EventArgs.Empty);
        }

        private void txtLastName_TextChanged(object sender, EventArgs e)
        {
            ValidateTextBox(txtLastName, EventArgs.Empty);
        }

        private void txtAge_TextChanged(object sender, EventArgs e)
        {
            ValidateTextBox(txtAge, EventArgs.Empty);
        }

        private void dateTimePickerDOB_ValueChanged(object sender, EventArgs e)
        {

        }

        private void txtAddress_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtContactNo_TextChanged(object sender, EventArgs e)
        {
            ValidateTextBox(txtContactNo, EventArgs.Empty);
        }

        private void txtWeight_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtHeight_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtHealthIssue_TextChanged(object sender, EventArgs e)
        {

        }

        private void rdoBPYes_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void rdoBPNo_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void rdoSugarNo_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void rdoSugarYes_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void cmbPackage_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void txtAmount_TextChanged(object sender, EventArgs e)
        {

        }

        private void dateTimePickerDOJ_ValueChanged(object sender, EventArgs e)
        {

        }

        private void txtDOB_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtDOJ_TextChanged(object sender, EventArgs e)
        {

        }

        private void addpladfn_FormClosed(object sender, FormClosedEventArgs e)
        {
            stopCamera();
        }

        private byte[] conv_photo()
        {
            //converting photo to binary data
            if (pictureBoxMember.Image != null)
            {
                //using FileStream:(will not work while updating, if image is not changed)
                //FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
                //byte[] photo_aray = new byte[fs.Length];
                //fs.Read(photo_aray, 0, photo_aray.Length);  

                //using MemoryStream:
                ms = new MemoryStream();
                pictureBoxMember.Image.Save(ms, ImageFormat.Jpeg);
                byte[] photo_aray = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(photo_aray, 0, photo_aray.Length);
               // cmd.Parameters.AddWithValue("@photo", photo_aray);
                return photo_aray;
                
            }
            return null;
        }

        private void fetchMemberById(int id)
        {
            try
            {
                SqlCommand sqlCommand = new SqlCommand("select m.*,sp.type from  member m LEFT JOIN subscription_plan sp ON m.mem_plan=sp.id where m.id=" + id, con);
                con.Open();
                SqlDataReader reader = sqlCommand.ExecuteReader();

                if (reader != null)
                {
                    while (reader.Read())
                    {
                        textBoxMemId.Text = reader["mem_id"].ToString();
                        
                        txtFirstName.Text = reader["firstname"].ToString() ;
                      
                       txtLastName.Text=reader["lastname"].ToString();

                       String gender = reader["gender"].ToString();

                       if (gender == "Male")
                       {
                           rdoMale.Checked =true;
                       }

                       else if (gender == "Female")
                       {
                           rdoFemale.Checked = true;
                       }

                       String dob = reader["dob"].ToString();

                       if (dob != null && dob.Length > 0)
                       {
                           dateTimePickerDOB.Value = DateTime.Parse(dob);
                       }
                       
                       txtAge.Text = reader["age"].ToString();

                       txtHeight.Text = reader["height"].ToString();

                       txtWeight.Text = reader["weight"].ToString();

                       String bloodPressure = reader["blood_pressure"].ToString();

                       if (bloodPressure == "Yes")
                       {
                           rdoBPYes.Checked = true;
                       }else if(bloodPressure=="No"){
                           rdoBPNo.Checked = true;
                       }

                       String sugar = reader["sugar"].ToString();

                       if (sugar == "Yes")
                       {
                           rdoSugarYes.Checked = true;
                       }
                       else if (sugar == "No")
                       {
                           rdoSugarNo.Checked = true;
                       }

                       txtAddress.Text=reader["address"].ToString();
                       
                       txtContactNo.Text = reader["contactno"].ToString();
                       
                       txtHealthIssue.Text=reader.GetString(10);

                       String doj = reader["dateofjoining"].ToString();

                       if (doj != null && doj.Length > 0)
                       {
                           dateTimePickerDOJ.Value = DateTime.Parse(doj);
                       }

                       String memPlanId = reader["type"].ToString();
                       if (memPlanId != null)
                       {
                           cmbPackage.Text = memPlanId;
                       }
                      
                        if (!reader.IsDBNull(17))
                       {
                           photo_aray = (byte[])reader["image"];
                           MemoryStream ms = new MemoryStream(photo_aray);
                           pictureBoxMember.Image = Image.FromStream(ms);
                       }
                     
                    }
                }

            }
            finally
            {
                con.Close();
            }
        }

        void fetchMemberPlan()
        {
            try
            {
                SqlDataAdapter adapt = new SqlDataAdapter("select id,type from subscription_plan", con);
                DataTable dt = new DataTable();
                adapt.Fill(dt);
                cmbPackage.DataSource = dt;
                cmbPackage.ValueMember = "id";
                cmbPackage.DisplayMember = "type";
            }
            catch
            {
                MessageBox.Show("Connection to server failed");
            }
            
        }
        private string fetchMemberPlan(String id){
            String type=null;
            SqlCommand sqlCommand = new SqlCommand("select type from subscription_plan where id=" + id, con);
              //  con.Open();
                SqlDataReader reader = sqlCommand.ExecuteReader();

                if (reader != null)
                {
                    while (reader.Read())
                    {
                        type=reader["type"].ToString();
                    }
                }
              //  con.Close();
            return type;
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void getMemberId()
        {
            SqlCommand cmd = new SqlCommand("select isnull(max(id),0)+1 as id from member  ", con);
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader != null)
            {
                while (reader.Read())
                {
                    textBoxMemId.Text = reader["id"].ToString();
                }
            }
            con.Close();

        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void checkBoxExistingMember_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxExistingMember.Checked)
            {
                textBoxMemId.ReadOnly = false;
            }
            else
            {
                textBoxMemId.ReadOnly = true;
            }
        }

        private void txtAge_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
        }

        private void txtContactNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
        }

        private void txtWeight_KeyPress(object sender, KeyPressEventArgs e)
        {
            // allows 0-9, backspace, and decimal
            if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
            {
                e.Handled = true;
                return;
            }

            // checks to make sure only 1 decimal is allowed
            if (e.KeyChar == 46)
            {
                if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
                    e.Handled = true;
            }
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void t(object sender, EventArgs e)
        {

        }

        private void textBoxMemId_TextChanged(object sender, EventArgs e)
        {
            ValidateTextBox(textBoxMemId, EventArgs.Empty);
        }
     
    }
}
